package com.blb.marrysystem.code;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@Controller
public class CodeServlet{
    private final Color[] COLORS = {Color.gray,Color.CYAN,Color.green,Color.magenta};
    private final String CHARS="abcdefghijklmnopqrstuvwxyz0123456789";
    @RequestMapping("/code")
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedImage bufferedImage = new BufferedImage(80, 30, BufferedImage.TYPE_3BYTE_BGR);//构造图片对象
        Graphics graphics = bufferedImage.getGraphics();//获得绘图对象
        graphics.fillRect(0,0,80,30); //填充长方形
        graphics.setFont(new Font("宋体",Font.BOLD,18));//设置字体格式
        String s = "";
        for(int i=1;i<=4;i++){
                char c = CHARS.charAt(new Random().nextInt(CHARS.length()));
                s=s+c;
                graphics.setColor(COLORS[new Random().nextInt(4)]);
                graphics.drawString(String.valueOf(c),18*(i-1)+10,18);
        }
        if(req.getSession().getAttribute("code")!=null){
            req.getSession().removeAttribute("code");
        }
        req.getSession().setAttribute("code",s);
        resp.setHeader("Cache-Control","no-cache");
        ImageIO.write(bufferedImage,"PNG",resp.getOutputStream());
    }
}
